package com.yups.dao;

import com.yups.utils.MD5Utils;
import com.yups.model.Emp;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 于鹏生
 */
public class EmpDao extends BaseDao {
	public boolean add(Emp emp) {
		try {
			String sql = "INSERT INTO db_book.emp ( NAME, mob, PASSWORD, email)\n" +
					"VALUES\n" +
					"  (?,?,?,?)";
			return queryRunner.execute(sql,
					emp.getName(),
					emp.getMob(),
					MD5Utils.stringToMD5(emp.getPassword(), emp.getMob()),
					emp.getEmail()
			) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean delete(int id) {
		try {
			String sql = "DELETE\n" +
					" FROM\n" +
					"  emp\n" +
					"WHERE id = ?";
			return queryRunner.execute(sql, id) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean update(Emp emp) {
		try {
			String sql = "UPDATE\n" +
					"  emp\n" +
					" SET\n" +
					"  NAME = ?, \n" +
					"  mob = ? \n" +
					"  email = ? \n" +
					" WHERE id = ?";
			return queryRunner.execute(sql,
					emp.getName(),
					emp.getMob(),
					emp.getEmail(),
					emp.getId()
			) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean updatePassword(Emp emp) {
		try {
			String sql = "UPDATE\n" +
					"  emp\n" +
					" SET\n" +
					"  password = ?" +
					" WHERE id = ?";
			return queryRunner.execute(sql,
					MD5Utils.stringToMD5(emp.getPassword(), emp.getMob()),
					emp.getId()
			) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public Emp get(int id) {
		try {
			String sql = "SELECT  id,NAME,mob,email FROM emp "
					+ " where id = ?";
			return queryRunner.query(sql, new BeanHandler<>(Emp.class), id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Emp get(String mob, String email) {
		try {
			String sql = "SELECT  id,NAME,mob FROM emp "
					+ " where mob = ? and email=?";
			return queryRunner.query(sql, new BeanHandler<>(Emp.class), mob, email);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Emp login(String mob, String password) {
		try {
			String sql = "SELECT  id,NAME,mob FROM emp "
					+ " where mob = ? and PASSWORD=?";
			return queryRunner.query(sql, new BeanHandler<>(Emp.class), mob,
					MD5Utils.stringToMD5(password, mob));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<Emp> getAll() {
		try {
			String sql = "SELECT  id,NAME,mob,email FROM emp "
					+ " order by id";
			return queryRunner.query(sql, new BeanListHandler<>(Emp.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}
